package beautiful.butterfly.distributed_service_container.socket.marshalling;

import beautiful.butterfly.distributed_service_container.socket.pojo.Request;
import beautiful.butterfly.distributed_service_container.socket.pojo.Response;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;


public class ClientHandler extends ChannelHandlerAdapter
{
    private static final Logger log = LoggerFactory.getLogger(ClientHandler.class);


    private Request request;
    //
    private CountDownLatch countDownLatch;
    private Response response;

    public ClientHandler()
    {
    }

    public ClientHandler(Request request, CountDownLatch countDownLatch)
    {
        System.out.println("任务初始化");
        this.request = request;
        this.countDownLatch = countDownLatch;
    }

    public Response getResponse()
    {
        return response;
    }

    public void channelActive(ChannelHandlerContext channelHandlerContext)
    {
        System.out.println("发送请求");
        channelHandlerContext.write(request);
        channelHandlerContext.flush();
    }

    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg)
            throws Exception
    {
        System.out.println("返回响应");
        //读取信息
        Response response = (Response) msg;
        System.out.println("xx" + response);
        this.response = response;
        this.countDownLatch.countDown();
    }

    public void channelReadComplete(ChannelHandlerContext channelHandlerContext) throws Exception
    {
        channelHandlerContext.flush();
        log.info("返回响应channelReadComplete");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause)
    {
        cause.printStackTrace();
        channelHandlerContext.close();
        //
        this.response = Response.newResponse(this.request);
        this.response.setErrorCode(Response.error);
        this.response.setErrorMessage(cause.getMessage());
        this.countDownLatch.countDown();
        System.out.println("返回响应exceptionCaught");

    }
}
